<template>
	<div class="">
		<div ref="amapRef" class="w-full h-full"></div>
	</div>
</template>

<script setup lang="ts">
import { useScript } from '/@/hooks/web/useScript';
const A_MAP_URL = 'https://webapi.amap.com/maps?v=1.4.15&key=24a6afd6ab0b81c1bda89e736ff24c6f';
const amapRef = ref();
const { toPromise } = useScript({ src: A_MAP_URL });
const props = defineProps({
	latitude: {
		type: Number,
		default: 0,
	},
	longitude: {
		type: Number,
		default: 0,
	},
});
let map: any;
let AMap: any;
let marker: any;
async function initMap() {
	await toPromise();
	const wrapEl = unref(amapRef);
	if (!wrapEl) return;
	AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
	});
	await nextTick(() => {
		if (props.latitude && props.longitude) {
			const ct = new AMap.LngLat(props.longitude, props.latitude);
			map.setZoomAndCenter(14, ct);
		}
		marker = new AMap.Marker({
			clickable: true,
			position: [props.longitude, props.latitude],
		});
		marker.setMap(map);
	});
}
const handleMarkerPos = (location: { longitude: number; latitude: number }) => {
	const ct = new AMap.LngLat(location.longitude, location.latitude);
	if (!marker) {
		marker = new AMap.Marker({
			clickable: false,
			position: ct,
		});
		marker.setMap(map);
	}
	marker.setPosition(ct);
	map.setCenter(ct);
};
onMounted(() => {
	nextTick(() => {
		initMap();
	});
});
defineExpose({
	handleMarkerPos,
});
</script>

<style lang="scss" scoped>
:deep(.amap-marker-label) {
	color: #000;
	background: #00e400;
	border: unset;
	border-radius: 4px;
}
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
</style>
